<template>
  <el-dialog :before-close="onCancel" :lock-scroll="false" title="知识库"
             :visible.sync="visible"
             width="950px">
    <el-form :model="form" ref="form">
      <div style="margin-bottom: 10px"></div>
      <div style="margin-left: 10px">
        <el-table :data="form.articles" border :header-cell-style="{'text-align':'center'}" v-loading="loading"
                  :cell-style="{'text-align':'center'}">
          <el-table-column type="index" label="序号" fixed width="50"></el-table-column>

          <el-table-column label="标题" width="210">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`articles.${scope.$index}.id`"
                            :rules="{required: true, message: '标题为必需', trigger: 'blur'}">
                <el-select
                  @input="((data)=>changeTitle(data,scope.$index))"
                  v-model="scope.row.id"
                  filterable
                  remote
                  clearable
                  placeholder="请输入关键词"
                  :remote-method="(query)=>remoteMethod(query,scope.$index)"
                  :loading="titleLoading">
                  <el-option
                    :disabled="form.articles.some(val=>val.id===item.id)"
                    v-for="item in optionsList[scope.$index]"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id">
                    <span style="float: left">标题：  {{ item.title }}</span> &nbsp;&nbsp;&nbsp;&nbsp;
                    <span style="float: right">栏目：  {{ item.cate_name ? item.cate_name : '无' }}</span>
                    <el-divider/>
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="所属栏目" width="220">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`articles.${scope.$index}.cate_name`"
              >
                <el-input placeholder="所属栏目" disabled
                          v-model="scope.row.cate_name"/>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="创建人" width="220">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`articles.${scope.$index}.create_user_name`"
              >
                <el-input placeholder="创建人" disabled
                          v-model="scope.row.create_user_name"/>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="创建时间" width="220">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`articles.${scope.$index}.create_time`"
              >
                <el-input placeholder="创建时间" disabled
                          v-model="scope.row.create_time"/>
              </el-form-item>
            </template>
          </el-table-column>


          <el-table-column label="操作" fixed="right" width="160">

            <template slot-scope="scope">
              <el-tooltip content="删除" :open-delay="700" placement="top">
              <el-link type="danger"  :underline="false" style="font-size: 18px" icon="el-icon-delete"
                       @click="delList(scope.$index)"></el-link>
              </el-tooltip>
              <el-tooltip content="查看详情" :open-delay="700" placement="top">
              <el-link type="primary" :underline="false" style="font-size: 18px" icon="el-icon-view"
                       :disabled="!scope.row.id"
                       @click="toDetail(scope.row.id)"></el-link>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div class="add-btn" @click="addList" style="margin-top: 5px"><i class="el-icon-plus"></i></div>
      </div>
    </el-form>
    <div slot="footer">
      <el-button @click="onCancel()">取消</el-button>
      <el-button :loading="btnLoading" type="primary" @click="onSave('form')">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: "product-form",
  props: ['typeList'],
  components: {},
  data() {
    return {
      loading: false,
      visible: false,
      options: [],
      optionsList: [],
      titleLoading: false,
      btnLoading: false,
      row: '',
      form: {
        articles: [
          {
            id: '',
            title: '',
            cate_id: '',
            cate_name: '',
            create_user_id: '',
            create_user_name: '',
            create_time: ''
          }
        ]
      },
    }
  },
  // created() {
  //   this.remoteMethod(null, 0)
  // },
  watch: {},
  methods: {
    changeTitle(id, index) {
      let newData
      if (id) newData = {...this.optionsList[index].find(item => item.id === id)}
      else newData = {}
      this.$set(this.form.articles, index, newData)
    },
    addList() {
      this.form.articles.push(
        {
          id: '',
          title: '',
          cate_id: '',
          cate_name: '',
          create_user_id: '',
          create_user_name: '',
          create_time: ''
        }
      )
      this.optionsList.push(JSON.parse(JSON.stringify(this.options)))
    },
    delList(index) {
      this.$confirm("是否确认删除？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false
      }).then(() => {
        this.form.articles.splice(index, 1)
        this.optionsList.splice(index, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /*查看知识库详情*/
  toDetail(id){
    this.visible = false;
    this.$router.push({
      path: `/content/article/detail?id=${id}`,
    })
  },


    showDialog(row) {
      this.visible = true;
      this.$nextTick(() => {
        if (row.id) {
          this.row = row
          this.loading = true
          this.$http.get(`/product_types/${row.id}`).then(res => {
            if (res.data.code === 0) {
              this.form.articles = res.data.data.articles
              if (this.form.articles.length > 0) {
                this.optionsList = this.form.articles.map(() => [...res.data.data.articles])
              }
              this.remoteMethod(null, this.form.articles.length)
              this.form.articles.push({
                id: '',
                title: '',
                cate_id: '',
                cate_name: '',
                create_user_id: '',
                create_user_name: '',
                create_time: ''
              })
            } else {
              this.$message.error(res.data.msg);
            }
            this.loading = false;
          }).catch(err => {
            new Error(err)
          })
        }
      })
    },
    onSave(val) {
      this.$refs[val].validate((valid) => {
        if (valid) {
          let article_ids = this.form.articles.map(item => {
            return item.id
          })
          this.handleAssociateContent(article_ids)
        }


      });

    },
    onCancel() {
      this.form = {
        articles: [
          {
            id: '',
            title: '',
            cate_id: '',
            cate_name: '',
            create_user_id: '',
            create_user_name: '',
            create_time: ''
          }
        ]
      },
        this.visible = false;
    },
    remoteMethod(query, index) {
      this.titleLoading = true;
      this.$http.get(`/article/index?`, {params: {title: query,status:1}}).then(res => {
        if (res.data.code === 0) {
          this.titleLoading = false;
          this.optionsList[index] = res.data.data
          if (!query) this.options = res.data.data
        } else {
          this.titleLoading = false;
          this.$message.error(res.data.msg);
        }
      })

    },
    handleAssociateContent(article_ids) {
      this.btnLoading = true
      this.row.article_ids = article_ids
      this.$http.put(`/product_types/${this.row.id}`, {...this.row}).then(res => {
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.onCancel();
          this.$emit("reload")
        } else {
          this.$message.error(res.data.msg);
        }
        this.btnLoading = false;
      })
    },
  }
}
</script>

<style scoped lang="scss">

.el-dialog:not(.ele-dialog-form) .el-dialog__body .el-form .el-form-item:last-child {
  margin-bottom: 0;
}

::v-deep .el-input {
  width: 100%;
}

.add-btn {

  height: 57px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2px dashed var(--color-primary);
  //letter-spacing:1rem;
  i {
    font-size: 18px;
    color: var(--color-primary);
    font-weight: bolder;
  }

  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
    cursor: pointer;
  }

  &:active {
    color: var(--color-primary-7);
    border-color: var(--color-primary-7);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
  }
}

</style>
